package executor;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author tongchen
 * @create 2023-02-11 19:35
 */
public class ReentrantLockRTest {
    public static int num=0;
    public static void main(String[] args) throws InterruptedException {
        //创建锁
        ReentrantLock reentrantLock = new ReentrantLock();
        //休眠一段时间
        TimeUnit.SECONDS.sleep(1);
        //创建线程1
         Thread t1 =new Thread(()->{
                   for (int i=0;i<50000;++i){
                       try{
                           reentrantLock.lock();
                           num++;
                       }catch (Exception e){
                           e.printStackTrace();
                       }finally {
                           reentrantLock.unlock();
                       }
                       //加锁
                       //解锁
                   }
                 });
         Thread t2 =new Thread(()->{
                   for (int i=0;i<50000;++i){
                       try{
                           reentrantLock.lock();
                           num++;
                       }catch (Exception e){
                           e.printStackTrace();
                       }finally {
                           reentrantLock.unlock();
                       }
                       //加锁
                       //解锁
                   }
                 });
         t1.start();
         t2.start();
         t1.join();
         t2.join();
        System.out.println(num);
    }
}
